package com.szwistar.common.comm;

import org.apache.mina.transport.serial.SerialAddress;

public class SerialAddressEx extends SerialAddress {
	private static final long serialVersionUID = 4631917237407995194L;

	public SerialAddressEx(String name, int bauds, DataBits dataBits, StopBits stopBits, Parity parity, FlowControl flowControl) {
		super(name, bauds, dataBits, stopBits, parity, flowControl);
	}

	public SerialAddressEx(SerialAddress another) {
		super(another.getName(), another.getBauds(), another.getDataBits(), another.getStopBits(), another.getParity(), another.getFlowControl());
	}

	@Override
	public String toString() {
		int databits = 8;
		switch(getDataBits()) {
			case DATABITS_8: databits = 8; break;
			case DATABITS_7: databits = 7; break;
			case DATABITS_6: databits = 6; break;
			case DATABITS_5: databits = 5; break;
			default: break;
		}

		String stopbits = "1";
		switch(getStopBits()) {
			case BITS_1: stopbits = "1"; break;
			case BITS_2: stopbits = "2"; break;
			case BITS_1_5: stopbits = "1.5"; break;
			default: break;
		}

		String parity = "n";
		switch(getParity()) {
			case NONE: parity = "n"; break;
			case ODD: parity = "o"; break;
			case EVEN: parity = "e"; break;
			case MARK: parity = "m"; break;
			case SPACE: parity = "s"; break;
			default: break;
		}

		return String.format("%s:%d,%d,%s,%s", getName(), getBauds(), databits, parity, stopbits);
	}

	public static SerialAddressEx fromString(String str) throws Exception {
		// 参数格式为: "UART1:115200,8,n,1"
		String[] parts = str.split("[:,]");
		if((parts == null) || (parts.length != 5)) {
			throw new Exception("非法的串口参数: " + str);
		}

		String name = parts[0];
		int baud = Integer.parseInt(parts[1]);
		DataBits dataBits = DataBits.DATABITS_8;
		StopBits stopBits = StopBits.BITS_1;
		Parity parity = Parity.NONE;

		switch(parts[2]) {
			case "8": dataBits = DataBits.DATABITS_8; break;
			case "7": dataBits = DataBits.DATABITS_7; break;
			case "6": dataBits = DataBits.DATABITS_6; break;
			case "5": dataBits = DataBits.DATABITS_5; break;
			default: throw new Exception("非法的数据位定义: " + parts[2]);
		}

		switch(parts[3]) {
			case "n": parity = Parity.NONE; break;
			case "o": parity = Parity.ODD; break;
			case "e": parity = Parity.EVEN; break;
			case "m": parity = Parity.MARK; break;
			case "s": parity = Parity.SPACE; break;
			default: throw new Exception("非法的校验位定义: " + parts[3]);
		}

		switch(parts[4]) {
			case "1": stopBits = StopBits.BITS_1; break;
			case "2": stopBits = StopBits.BITS_2; break;
			case "1.5": stopBits = StopBits.BITS_1_5; break;
			default: throw new Exception("非法的停止位定义: " + parts[4]);
		}

		return new SerialAddressEx(name, baud, dataBits, stopBits, parity, FlowControl.NONE);
	}
}
